package com.only4play.portal.web.resource;

import com.only4play.portal.cp.api.CpService;
import com.only4play.portal.cp.bean.message.jsonmessage.CpJsonMessage;
import com.only4play.portal.cp.bean.message.jsonmessage.CpJsonOutMessage;
import com.only4play.portal.web.config.PortalJsonCpConfiguration;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author liyuncong
 * @version 1.0
 * @file PortalResource
 * @brief PortalResource
 * @details PortalResource
 * @date 2024-06-07
 *
 * Edit History
 * ----------------------------------------------------------------------------
 * DATE                     NAME               DESCRIPTION
 * 2024-06-07               liyuncong          Created
 */

@Slf4j
@RestController
@RequestMapping("/cp/portal/{agentId}")
public class PortalResource {

    @PostMapping(produces = MediaType.APPLICATION_JSON_VALUE)
    public String doHandleJsonMessage(
        @PathVariable Integer agentId,
        @RequestBody String requestBody,
        @RequestParam("msg_signature") String signature,
        @RequestParam("timestamp") String timestamp,
        @RequestParam("nonce") String nonce,
        HttpServletRequest request
    ) {
        log.info("received json message request :[signature=[{}], timestamp=[{}], nonce=[{}], requestBody=[\n{}\n]]",
            signature, timestamp, nonce, requestBody);

        // 参数校验
        if (StringUtils.isAnyBlank(signature, timestamp, nonce)) {
            throw new IllegalArgumentException("请求参数非法，请核实!");
        }

        final CpService portalCpService = PortalJsonCpConfiguration.getCpService(agentId);

        // 消息解密
        CpJsonMessage jsonMessage = CpJsonMessage.fromEncryptedJson(requestBody, portalCpService.getCpConfigStorage(),
            timestamp, nonce, signature);

        // 消息处理
        CpJsonOutMessage jsonOutMessage = this.route(agentId, jsonMessage);
        if (jsonOutMessage == null) {
            return "";
        }

        // 响应消息加密
        String encryptedJson = jsonOutMessage.toEncrypted(portalCpService.getCpConfigStorage());

        log.info("handler finished, outputMsg: [encryptedJson=[{}]]", encryptedJson);
        return encryptedJson;
    }

    private CpJsonOutMessage route(Integer agentId, CpJsonMessage jsonMessage) {
        try {
            return PortalJsonCpConfiguration.getRouters().get(agentId).route(jsonMessage);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        return null;
    }

}
